package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.test4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticelDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ZQH
 * @version 1.0
 * @date 2023/8/9 21:53
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 自媒体文章审核
     * @param id  自媒体文章id
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (StringUtils.isEmpty(wmNews)){
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT)){
        //从内容中提取纯文本内容 和图片
        Map<String,Object> textAndImages = handleTextAndImages(wmNews);

        //自管理的敏感词
            boolean isSensitiveScan = handleSensitiveScan(textAndImages.get("content").toString(),wmNews);
            if (isSensitiveScan) return;

        //审核文本内容  阿里云接口
            boolean isTextScan = handleTextScan(textAndImages.get("content").toString(),wmNews);
            if (isTextScan) return;
            //审核图片  阿里云
            boolean isImagesScan = handleImagesScan((List<String>) textAndImages.get("images"),wmNews);
            if (isImagesScan) return;
            //审核成功保存app端的相关文章数据
            ResponseResult responseResult = saveAppWmNews(wmNews);
            if (responseResult.getCode() != 200){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关内容失败");
            }
            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, (short) 9,"审核成功");
        }



    }

    @Autowired
    private WmSensitiveMapper sensitiveMapper;

    /**
     * 自管理的敏感词
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        //获取所有敏感词
        List<WmSensitive> wmSensitives = sensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery()
        .select(WmSensitive::getSensitives));

        List<String> stringList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词
        SensitiveWordUtil.initMap(stringList);
        // 查看文章中是否包含敏感词
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(content);
        if (matchWords.size() > 0){
            this.updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容："+matchWords);
            flag = false;
        }
        return flag;
    }

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    /**
     * 保存app端的相关文章数据
     * @param wmNews
     */
    private ResponseResult saveAppWmNews(WmNews wmNews) {
        ArticelDto dto = new ArticelDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (!StringUtils.isEmpty(wmChannel)){
            dto.setChannelName(wmChannel.getName());
        }
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (!StringUtils.isEmpty(wmUser)){
            dto.setAuthorName(wmUser.getName());
        }
        //设置文章ID
        if (!StringUtils.isEmpty(wmNews.getArticleId())){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        ResponseResult result = articleClient.saveArticle(dto);

        return result;
    }

    @Autowired
    private Tess4jClient tess4jClient;
    @Autowired
    private FileStorageService fileStorageService;
    /**
     * //审核图片  阿里云
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images == null && images.size() ==0){
            return flag;
        }
        List<byte[]> imagesList = new ArrayList<>();
        //去重复
        images = images.stream().distinct().collect(Collectors.toList());
        //下载图片
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                //图片识别
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(byteArrayInputStream);
                String reslut = tess4jClient.doOCR(read);
                //过滤文字
                boolean isSenstive = handleSensitiveScan(reslut, wmNews);
                if (!isSenstive){
                    return isSenstive;
                }
                imagesList.add(bytes);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //审核图片
            Map map = greenImageScan.imageScan(imagesList);
            if ("block".equals(map.get("suggestion"))){
                flag = updateWmNews(wmNews, (short) 1, "当前文章中存在违规");
            }else if ("review".equals(map.get("suggestion"))){
                flag = updateWmNews(wmNews,(short) 3, "当前文章中存不确定内容");
            }
        } catch (Exception exception) {
            flag = false;
        }
        return flag;
    }

    /**
     * 审核文本内容  阿里云接口
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        String titleContent = wmNews.getTitle() +"-"+ content;
        if (titleContent.length() ==0){
            return true;
        }
        //审核失败修改文章状态
        try {
            Map map = greenTextScan.greeTextScan(titleContent);
            if ("block".equals(map.get("suggestion"))){
                flag = updateWmNews(wmNews, (short) 1, "当前文章中存在违规");
            }else if ("review".equals(map.get("suggestion"))){
                flag = updateWmNews(wmNews,(short) 3, "当前文章中存不确定内容");
            }
        } catch (Exception exception) {
            flag = false;
            exception.printStackTrace();
        }
        return flag;

    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private boolean updateWmNews(WmNews wmNews,short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
        return false;
    }

    /**
     * 从内容中提取纯文本内容 和图片
     * 提前文章的封面图
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //存储纯文本内容
        StringBuilder stringBuilder = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();
        Map<String, Object> textAndImages = new HashMap<>();
        if (!StringUtils.isEmpty(wmNews.getContent())){
            List<Map> jsonArray = JSON.parseArray(wmNews.getContent(),Map.class);
            for (Map map : jsonArray) {
                if ("text".equals(map.get("type"))){
                    stringBuilder.append(map.values());
                }else if ("image".equals(map.get("type"))){
                    images.add(map.values().toString());
                }
            }
        }
        //提取文章的封面
        if (!StringUtils.isEmpty(wmNews.getImages())){
            String newsImages = wmNews.getImages();
            String[] split = newsImages.split(",");
            images.addAll(Arrays.asList(split));
        }
        textAndImages.put("content",stringBuilder.toString());
        textAndImages.put("images",images);
        return textAndImages;
    }
}
